import {CHANNEL_LOCAL_KEY} from "@/store/constants";
import http from "@/utils/http";
import {createAction} from "redux-actions";
import {
  ADDCHANNEL,
  DELCHANNEL,
  SETRESTCHANNELS,
  UPDATEACTIVECHANNELKEY,
  UPDATEARTICLE,
  UPDATECHANNELS
} from "@/store/actionTypes";
import {differenceBy} from "lodash";


// 创建action对象的方法
const updateUserChannels = createAction(UPDATECHANNELS)
const setRestChannels = createAction(SETRESTCHANNELS)
export const updateActiveChannelKey = createAction(UPDATEACTIVECHANNELKEY)
const delChannelsAction = createAction(DELCHANNEL)
const addArticle = createAction(UPDATEARTICLE)
/**
 * 创建添加频道action对象
 * @type {(function(): {type: *})|*}
 */
const addChannel = createAction(ADDCHANNEL)

/**
 * 获取用户频道信息
 * @return {(function(*, *): Promise<void>)|*}
 */
export const getUserChannel = () => {
  return async (dispatch, getState) => {
    // 1、判读用户是否登录,拿到token做判断
    const {login: {token}} = getState()
    // 2、判断一下本次存储是否有数据
    let userChannels
    // 获取到本地存储的频道数据
    const localChannels = JSON.parse(localStorage.getItem(CHANNEL_LOCAL_KEY) || '[]')

    //  3、首先判读需要请求接口的用户状态
    if (token || !localChannels.length) {
      // 登录了或者本地存储没数据
      // console.log('请求接口')
      const {data: {channels}} = await http.get('/user/channels')
      localStorage.setItem(CHANNEL_LOCAL_KEY, JSON.stringify(channels))
      userChannels = channels
    } else {
      // 没有登录并且本地存储有数据
      // console.log('使用本地存储的数据')
      userChannels = localChannels
    }

    // FIXME: 验证本地存储是否有channels数据
    // TODO: userChannels写入redux中
    dispatch(updateUserChannels(userChannels))
  }
}

/**
 * 处理推荐频道信息
 * @return {(function(*, *): Promise<void>)|*}
 */
export const getRestChannels = () => {
  return async (dispatch, getState) => {
    //  获取当前用户的频道数据
    //  获取所有的频道数据
    //  进行剔除 => 拿到结果
    const {
      home: {userChannel}
    } = getState()
    const res = await http.get('/channels')
    const restChannels = differenceBy(res.data.channels, userChannel, 'id')
    // 差集的结果写入到redux里面去
    dispatch(setRestChannels(restChannels))
  }
}

/**
 * 删除频道数据的thunk函数
 * @param {Object} item 需要删除的频道项
 */
export const delChannel = (item) => {
  return async (dispatch, getState) => {
    // 是否登录状态
    const {login: {token}} = getState()
    if (token) {
      //  登录状态直接从接口里面删除频道数据即可
      await http.delete(`/user/channels/${item.id}`);
    } else {
      // 本地存储里面删除数据
      const localChannels = JSON.parse(localStorage.getItem(CHANNEL_LOCAL_KEY) || '[]')
      //   本地存储里面把需要删除的频道过滤掉，重新写入本地存储
      const userChannels = localChannels.filter(channel => channel.id !== item.id)
      localStorage.setItem(CHANNEL_LOCAL_KEY, JSON.stringify(userChannels))
    }

    dispatch(delChannelsAction(item)) // {id: '', name: ''}
  }
}
/**
 * 用于添加频道数据
 * @param {Object} item 需要添加的频道对象
 */
export const handleAddChannel = item => {
  return async (dispatch, getState) => {
    //  获取token判断是否登录
    const {login: {token}} = getState()
    // console.log(token)
    if (token) {
      //  处于登录的情况，需要添加到接口里面
      await http.patch(`/user/channels`, {channels: [item]})
    } else {
      //  操作本地存储
      const localChannels = JSON.parse(localStorage.getItem(CHANNEL_LOCAL_KEY) || '[]')
      const userChannels = [...localChannels, item];
      localStorage.setItem(CHANNEL_LOCAL_KEY, JSON.stringify(userChannels))
    }

    // 问题：修改完了之后，界面没有实时响应，界面刷新，效果又有了
    // redux ==> 界面数据
    dispatch(addChannel(item))
  }
}

/**
 * 获取文章列表数据的thunk函数
 * @param {Number} channel_id 当前需要获取文章的频道id
 * @param {String} timestamp 请求数据的时间戳
 * @return {(function(*): Promise<void>)|*}
 */
export const getArticleList = (channel_id, timestamp) => {
  return async dispatch => {
    const res = await http.get('/articles', {
      params: {
        channel_id, // 文章的频道
        timestamp
      }
    })
    // console.log(res)

    dispatch(addArticle({
      channel_id,
      data: res.data
    }))

    //   获取到的数据存储到redux里面去
  //  channeid
  }
}
